import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:dio/dio.dart';
import '../../data/local/local_storage.dart';
import '../../data/remote/home_info.dart';
import '../../generated/assets.dart';
import '../../main.dart';
import '../../utils/toast_utils.dart';

class LoginPage extends StatefulWidget {
  const LoginPage({super.key});

  @override
  State<LoginPage> createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  final dio = Dio();
  TextEditingController usernameController = TextEditingController();
  TextEditingController passwordController = TextEditingController();
  String usernameText = '';
  String passwordText = '';
  String token = '';

  @override
  void initState() {
    super.initState();
  }

  void _onpUsernameTextChanged(String text) {
    // 这里可以实现具体的搜索逻辑，比如过滤列表等
    setState(() {
      usernameText = text;
    });
  }

  void _onpPasswordTextChanged(String text) {
    // 这里可以实现具体的搜索逻辑，比如过滤列表等
    setState(() {
      passwordText = text;
    });
  }

  void filterSearchResults(String query) {
    print('query===>$query');
    // List<String> dummySearchResult = []; // 示例数据列表，实际应用中可能是从数据库或API获取的
    // dummySearchResult = query.isEmpty
    //     ? list // 如果查询为空，显示全部数据
    //     : list.where((item) => item.toLowerCase().contains(query.toLowerCase())).toList();
    // setState(() {
    //   searchResults = dummySearchResult; // 更新UI显示结果
    // });
  }

  login() async {
    print('usernameText==>$usernameText');
    print('passwordText==>$passwordText');
    if (usernameText.isEmpty) {
      ToastUtils.show('账号不得为空');
    } else if (passwordText.isEmpty) {
      ToastUtils.show('密码不得为空');
    } else {
      try {
        final response = await dio.post(
            'http://www.cqjhzn.com/api/user/adminlogin',
            data: {"username": usernameText, "password": passwordText});
        if (response.statusCode == 200) {
          final data = response.data;
          print('data444===>${data}');

          if (response.data['code'] == 200) {
            HomeLoginData? newData = HomeLoginData?.fromJson(response.data);
            print('newData===>${newData.data}');
            // LocalStorage.setToken(newData.data!.accessToken!);
            SharedPreferencesManager().setToken(newData.data!.accessToken!);
            setState(() {
              token = newData.data!.accessToken!;
            });
            Navigator.pushAndRemoveUntil(
              context,
              MaterialPageRoute(builder: (context) =>const MyHomePage(title: '故障灯监测系统')),
                  (route) => false, // 这里的 `false` 表示移除所有页面
            );
          } else {
            HomeLoginErrData? errData =
                HomeLoginErrData?.fromJson(response.data);
            print('errData===>${errData.msg}');
            ToastUtils.show(errData.msg.toString());
          }
        }
      } catch (e) {
        print('Error: $e');
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Stack(
        alignment: AlignmentDirectional.topCenter,
        children: [
          Image.asset(Assets.imagesLoginBg,
              width: double.infinity,
              height: double.infinity,
              fit: BoxFit.cover),
          Column(
            children: [
              SizedBox(
                height: 110,
              ),
              Image.asset(Assets.imagesLoginLogo,
                  width: 160, height: 115, fit: BoxFit.cover),
              SizedBox(
                height: 50,
              ),
              Container(
                height: 90,
                padding: EdgeInsets.fromLTRB(15, 20, 15, 0),
                child: TextField(
                  controller: usernameController, // 控制搜索输入的控制器
                  // 设置文字样式
                  style: TextStyle(
                    fontSize: 20.0, // 字体大小
                    color: Colors.white, // 字体颜色
                  ),
                  decoration: InputDecoration(
                    // labelText: '搜索',
                    // labelStyle: TextStyle(color: Color(0xFF2D8BC2)),
                    filled: true,
                    fillColor: Color(0xFF1A2B40),
                    hintText: '请输入账号',
                    hintStyle: TextStyle(color: Color(0xFFC1C3D3)),
                    prefixIcon: Padding(
                      padding: EdgeInsets.all(12),
                      child: Image.asset(
                        Assets.imagesIcUsername,
                        width: 10,
                        // height: 31,
                      ),
                    ),
                    // 搜索图标
                    border: OutlineInputBorder(
                      borderRadius: BorderRadius.all(Radius.circular(2.0)),
                    ),
                    focusedBorder: OutlineInputBorder(
                      borderSide:
                          BorderSide(color: Color(0xFF2D8BC2)), // 激活时边框颜色为蓝色
                    ),
                    enabledBorder: OutlineInputBorder(
                      borderSide:
                          BorderSide(color: Color(0xFF2D8BC2)), // 激活时边框颜色为蓝色
                    ),
                  ),
                  onChanged: (value) {
                    // 当文本变化时调用
                    _onpUsernameTextChanged(value);
                  },
                ),
              ),
              Container(
                height: 90,
                padding: EdgeInsets.fromLTRB(15, 20, 15, 0),
                child: TextField(
                  controller: passwordController, // 控制搜索输入的控制器
                  obscureText: true,
                  style: TextStyle(
                    fontSize: 20.0, // 字体大小
                    color: Colors.white, // 字体颜色
                  ),
                  decoration: InputDecoration(
                    // labelText: '搜索',
                    // labelStyle: TextStyle(color: Color(0xFF2D8BC2)),
                    filled: true,
                    fillColor: Color(0xFF1A2B40),
                    hintText: '请输入密码',
                    hintStyle: TextStyle(color: Color(0xFFC1C3D3)),
                    prefixIcon: Padding(
                      padding: EdgeInsets.all(12),
                      child: Image.asset(
                        Assets.imagesIcPassword,
                        width: 10,
                        // height: 31,
                      ),
                    ),
                    // 搜索图标
                    border: OutlineInputBorder(
                      borderRadius: BorderRadius.all(Radius.circular(2.0)),
                    ),
                    focusedBorder: OutlineInputBorder(
                      borderSide:
                          BorderSide(color: Color(0xFF2D8BC2)), // 激活时边框颜色为蓝色
                    ),
                    enabledBorder: OutlineInputBorder(
                      borderSide:
                          BorderSide(color: Color(0xFF2D8BC2)), // 激活时边框颜色为蓝色
                    ),
                  ),
                  onChanged: (value) {
                    // 当文本变化时调用
                    _onpPasswordTextChanged(value);
                  },
                ),
              ),
              SizedBox(
                height: 20,
              ),
              SizedBox(
                  width: double.infinity,
                  height: 50,
                  child: Padding(
                    padding: EdgeInsets.symmetric(horizontal: 15),
                    child: TextButton(
                      style: ButtonStyle(
                        shape: MaterialStateProperty.all(RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(0))),
                        backgroundColor:
                            WidgetStateProperty.all<Color>(Color(0xFF3C7FB3)),
                        foregroundColor:
                            WidgetStateProperty.all<Color>(Colors.white),
                        padding: WidgetStateProperty.all<EdgeInsets>(
                            const EdgeInsets.all(10)),
                      ),
                      onPressed: () {
                        login();
                      },
                      child: Text(
                        '登录',
                        style: TextStyle(color: Colors.white, fontSize: 20),
                      ),
                    ),
                  ))
            ],
          )
        ],
      ),
    );
  }
}
